#!/usr/bin/perl
package TEdit::MediaFile::FLAC;

use strict;
use warnings qw( all );
use TEdit::MediaFile;
use TEdit::Exec;
use Audio::FLAC::Header;
our @ISA = ("TEdit::MediaFile");

sub init {
	my $self = shift;
	$self->{_data} = undef;
	$self->SUPER::_init();
	return $self->error("unable to read file") unless -r $self->{filename};
	my $ao = Audio::FLAC::Header->new($self->{filename});
	$self->{_data}{info} = $ao->info;
	$self->{_data}{tags} = $ao->tags;
	$self->{codec} = 'FLAC';
}

sub _mapping {
        {
                tracknum        => 'TRACKNUMBER',
                totaltracknums  => 'TRACKTOTAL',
                discnum         => 'DISCNUMBER',
                totaldiscnums   => 'DISCTOTAL',
                year            => 'DATE',
                genre           => 'GENRE',
                title           => 'TITLE',
                album           => 'ALBUM',
                artist          => 'ARTIST',
                albumartist     => 'ALBUMARTIST',
		isrc		=> 'ISRC',
	};
}

sub _native_read {
	my $self = shift;
	my $tag = shift;
	my $value = shift;
	if(exists($self->{_data}{tags}{$tag})) {
		return $self->{_data}{tags}{$tag};
	}
	return;
}

sub _native_write {
	my $self = shift;
	my $tag = shift;
	my $value = shift;

	#step 1, remove tag if exists:
	$self->_native_remove($tag);
	
	#metaflac's fault: no multiline strings in flac tagvalues
	$value =~ s/[\r\n]/ /g;
	
	my $eo = TEdit::Exec->new({
		input => $tag . '=' . $value . "\n",
		cmdargs => [
			$self->_metaflac_path(),
			'--import-tags-from=-',
			$self->{filename},
		],
	});
	die("error: " . $eo->error) if $eo->error;
	die("error running metaflac") if $eo->returncode();

	$self->{_data} = undef;
	$self->init;
}

sub _native_remove {
	my $self = shift;
	my $tag = shift;
	
	my $eo = TEdit::Exec->new({ 
		cmdargs => [
			$self->_metaflac_path(),
			'--remove-tag=' . $tag,
			$self->{filename},
		],
	});
	die("error: " . $eo->error) if $eo->error;
	die("error running metaflac") if $eo->returncode();
	
}

sub _metaflac_path {
	my $self = shift;
	unless(defined($TEdit::MediaFile::FLAC::metaflac_path)) {
		foreach my $trypath ( qw( 
        		/usr/bin/metaflac 
		        /usr/local/bin/metaflac 
		)) {
			if( -x $trypath) {
				$TEdit::MediaFile::FLAC::metaflac_path = $trypath;
				last;
			}
		}
	}
	return($TEdit::MediaFile::FLAC::metaflac_path) 
}

1;

__END__
